package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"fresh-box-mart/freshrpc/freshrpc"
	"fresh-box-mart/freshrpc/internal/svc"
	"fresh-box-mart/model/cache"
	"fresh-box-mart/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshListLogic {
	return &FreshListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshListLogic) FreshList(in *freshrpc.FreshListRequest) (*freshrpc.FreshListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("fresh_list_%d", in.Page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	var list []*freshrpc.FreshList
	if cacheData == "" {
		var err error
		list, err = mysql.FreshList(mysql.DB, in)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	return &freshrpc.FreshListResponse{
		List: list,
	}, nil
}
